import 'package:asmore/context_menu.dart';
import 'package:asmore/library.dart';
import 'package:asmore/util.dart';
import 'package:asmore/widgets/overlay_slider.dart';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/widgets.dart';

class MusicPlayerControlBar extends StatefulWidget {
  final ValueNotifier<Artwork?> work;

  const MusicPlayerControlBar(this.work, {super.key});

  @override
  State<MusicPlayerControlBar> createState() => _MusicPlayerControlBarState();
}

class _MusicPlayerControlBarState extends State<MusicPlayerControlBar> {
  final player = AudioPlayer();
  int index = 0;
  bool isPlaying = false;
  int duration = 0;
  int position = 0;

  double progress = 0.0;

  void togglePlayback() {
    if (widget.work.value != null && player.source == null) {
      player.play(DeviceFileSource(widget.work.value!.tracks[index].path));
      setState(() {
        isPlaying = true;
      });
    } else {
      if (isPlaying) {
        player.pause();
      } else {
        player.resume();
      }
      setState(() {
        isPlaying = !isPlaying;
      });
    }
  }

  void seekTo(double value) {
    if (duration == 0) return;
    player.seek(Duration(seconds: (value / 100 * duration).toInt()));
    setState(() {
      progress = value;
    });
  }

  @override
  void initState() {
    super.initState();
    widget.work.addListener(() {
      player.release();
      setState(() {
        isPlaying = false;
        player
            .setSource(DeviceFileSource(widget.work.value!.tracks[index].path));
      });
    });
    player.onDurationChanged.listen((Duration d) {
      print('Max duration: $d');
      setState(() => duration = d.inSeconds);
    });
    player.onPositionChanged.listen((Duration p) {
      print('Current position: $p');
      if (duration == 0) return;
      setState(() {
        position = p.inSeconds;
        progress = position / duration * 100;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 50,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(widget.work.value == null ? "None" : widget.work.value!.id),
          IconButton(
            icon: Icon(
              Icons.skip_previous,
            ),
            onPressed: widget.work.value == null
                ? null
                : () {
                    index = (index - 1) % widget.work.value!.tracks.length;
                    player.release();
                    player.play(DeviceFileSource(
                        widget.work.value!.tracks[index].path));
                  },
          ),
          IconButton(
            icon: Icon(
              isPlaying ? Icons.pause : Icons.play_arrow,
            ),
            onPressed: widget.work.value == null ? null : togglePlayback,
          ),
          IconButton(
            icon: Icon(
              Icons.skip_next,
            ),
            onPressed: widget.work.value == null
                ? null
                : () {
                    index = (index + 1) % widget.work.value!.tracks.length;
                    player.release();
                    player.play(DeviceFileSource(
                        widget.work.value!.tracks[index].path));
                  },
          ),
          Text(widget.work.value == null
              ? "null"
              : "${index + 1}/${widget.work.value!.tracks.length}"),
          Expanded(
            child: Slider(
              value: progress,
              onChanged: seekTo,
              min: 0.0,
              max: 100.0,
            ),
          ),
          Text(
              "${format(Duration(seconds: position))}/${format(Duration(seconds: duration))}"),
          OverlaySlider(onChange: (v) {
            player.setVolume(v);
            print("set volume: $v");
          },),
          PlayListMenu(),
        ],
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    player.dispose();
  }
}
